<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class M_lib_circulationfile1 extends MY_Model {
	
	protected $_table = "lib_circulationfile1";
	protected $_uid = "id";

	public function __construct(){
		parent::__construct();
	}	

	public function check_out()
	{
		$sly = new stdClass;
		$sly->status = false;
		$sly->msg = "";
		$sly->unavailable = false;

		unset($data);
		$data['trndte'] = $trndte = $this->input->post('trndte').' '.date('g:h:s');
		$data['usertype'] = $usertype = $this->input->post('usertype');
		$data['remarks'] = $this->input->post('remarks');
		$data['librarian_id'] = $this->session->userdata['userid'];
		$data['ay_id'] = $this->current_school_year;
		$data['borrower_id'] = $this->input->post('id'); // Emp_id or Enrollment_id
		
		$cart = $this->input->post('cart');
		$this->load->model('M_library_books');
		$this->load->model('M_lib_reservation','m_libres');
		$this->load->model('M_lib_circulationfile2','m_lib2');

		$borrow_items = false;
		$reserve_items = false;
		
		if($cart){

			/*************LOOP THE CART TO GET VALUE -> SEPARATE BORROW FORM RESERVE************/
				foreach ($cart as $book_id => $input) {
					$input = (object)$input;
					if($input->trntype === "borrow"){
						$borrow_items[$book_id] = $input;
					}else if($input->trntype === "reserve"){
						$reserve_items[$book_id] = $input;
					}else{}
				}

			/*************LOOP BORROW ITEMS AND PROCESS SAVING*************/
				if($borrow_items){

					/************ SAVE TRANSACTION TO lib_circulationfile1 **************/
						$rs_lib = (object)$this->insert($data);
						if(!$rs_lib->status){
							$sly->msg = "Checkout encountered an error, please try again";
							return $sly;
						}

					/************ SAVE TRANSACTION DETAILS TO lib_circulationfile2 **************/
						foreach ($borrow_items as $book_id => $input) {

							/** check books if still available - double checking **/
							$isavailable = $this->_check_book_if_available($book_id);
							if(!$isavailable){
								$sly->unavailable[] = $book_id; //book already unavailable
								continue;
							}

							/**	1 item is equal to 1 query
								reason : if the book is return separately **/
							unset($details);
							for($i = 1; $i <= intval($input->qty); $i++){
								unset($details);
								$details['circulation_id'] = $rs_lib->id;
								$details['media_id'] = $book_id;
								$details['trndte'] = $trndte;
								$details['cir_status'] = 'UNRETURN';
								$details['is_late'] = 0;
								$details['day_late'] = 0;
								$rs = (object)$this->m_lib2->insert($details);

								if($rs->status){

									/** Update Media / Item books_borrowed (add + 1) **/
									$this->db->query("UPDATE library_books set book_borrowed = book_borrowed + 1 WHERE book_id = ?", array($book_id));
								}
							}
						}
				}
			
			/*************LOOP RESERVE ITEMS AND PROCESS SAVING*************/
				if($reserve_items){

					/************ SAVE TRANSACTION TO lib_reservation **************/
						foreach ($reserve_items as $book_id => $input) {

							/**	1 item is equal to 1 query
								reason : if the book is borrowed separately **/
							unset($reserves);
							for($i = 1; $i <= intval($input->qty); $i++){
								unset($reserves);
								$reserves['circulation_id'] = $rs_lib->id;
								$reserves['media_id'] = $book_id;
								$reserves['trndte'] = $trndte;
								$reserves['cir_status'] = 'UNRETURN';
								$reserves['is_late'] = 0;
								$reserves['day_late'] = 0;
								$rs = (object)$this->m_libres->insert($reserves);
							}
						}
				}
			
			$sly->status = true;
			$sly->msg = "Transaction was successfully saved";
			return $sly;
		}

		$sly->msg = "Checkout failed, please try again";
		return $sly;
	}

	private function _check_book_if_available($book_id)
	{
		$q = $this->db->select('book_copies - book_borrowed as available')
				 ->where('book_id', $book_id)
				 ->get('library_books');

		if($q->num_rows() > 0){

			return $q->row()->available > 0 ? true : false;
		}

		return false;
	}

	/**
	 * Get Active Transactions
	 * @usertype student/employee
	 * @id enrollment_id/emp_id
	 * @return array of objects
	 */
	public function get_active_transactions($usertype, $id)
	{
		$q = $this->db->select('*')
					->where('usertype', $usertype)
					->where('borrower_id', $id)
					->where('is_deleted', 0)
					->where('status', 'UNRETURN')
					->order_by('trndte DESC, id DESC')
					->get($this->_table);

		$sly = false;

		if($q->num_rows() > 0){

			foreach ($q->result() as $key => $value) {
				
				/** Get Details **/
				$d = $this->db->select('lib_circulationfile2.*, library_books.book_name, library_books.book_desc')
				->where('lib_circulationfile2.circulation_id', $value->id)
				->where('lib_circulationfile2.is_deleted', 0)
				->join('library_books','lib_circulationfile2.media_id = library_books.book_id','left')
				->order_by('id')
				->get('lib_circulationfile2');

				$new = new stdClass;
				$new->header = $value;
				$new->details = $d->num_rows() > 0 ? $d->result() : false;

				$sly[] = $new;
			}

			return $sly;
		}

		return false;
	}

	/**
	 * Update Status
	 * Check if all media of the transaction was all returned and update status
	 */
	public function update_status($id)
	{
		$rs = $this->get($id);

		if($rs){

			/*** Get Unreturn Items ***/
			$q = $this->db->select('*')
			->where('circulation_id', $id)
			->where('is_deleted', 0)
			->where('cir_status <>','RETURN')
			->limit(1)
			->get('lib_circulationfile2');

			$status = $q->num_rows() > 0 ? 'UNRETURN' : 'RETURN';

			if($status != $rs->status){
				unset($data);
				$data['status'] = $status;
				$this->update($id, $data);
				return true;
			}
		}

		return false;
	}

	/**
	 * Remove Transaction
	 * Update is_deleted to 1
	 * @param id int
	 */
	public function delete_transaction($id)
	{
		unset($data);
		$data['is_deleted'] = 1;
		$data['date_deleted'] = NOW;
		$data['deleted_by'] = $this->session->userdata['userid'];
		$rs = $this->update($id, $data);
		
		if($rs){

			$this->load->model('M_lib_circulationfile2', 'm');

			/** FIND DETAILS AND UPDATE TO is_deleted 1 **/
			unset($get);
			$get['where']['circulation_id'] = $id;
			$get['where']['is_deleted'] = 0;
			$items = $this->m->get_record(false, $get);
			if($items){
				foreach ($items as $key => $i) {
					/** update book borrowed-1 **/
					$this->db->query("UPDATE library_books set book_borrowed = book_borrowed - 1 WHERE book_id = ?", array($i->media_id));
					
					$this->m->update($i->id, $data);
				}
			}

			return true;
		}

		return false;
	}
}